package com.lp.mgt.services.impls;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.lp.mgt.controllers.LoginCtr;
import com.lp.mgt.entities.User;
import com.lp.mgt.services.LoginService;
import com.lp.mgt.utils.SendMessageUtil;
@Service
public class LoginServiceImpl implements LoginService {
	private Logger logger = LoggerFactory.getLogger(LoginCtr.class);
	@Override
	public Boolean login(User user) {
		if("".equals(user.getUsername()) ||"".equals(user.getPassword())){
			logger.info("用户名和密码不能违抗!");
			return false;
		}
		Subject subject = SecurityUtils.getSubject();//安全操作
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        token.setRememberMe(user.getRememberMe()==null?false:true);
        //4.认证
        try {
        	subject.login(token);
        	return true;
		} catch ( UnknownAccountException uae ) { logger.info("用户不存在!");
		} catch ( IncorrectCredentialsException ice ) {logger.info("密码不正确 !");
		} catch ( DisabledAccountException lae ) { logger.info("用户被锁定!");
		} catch ( ExcessiveAttemptsException eae ) {logger.info("尝试认证次数多余系统指定次数 ");
		} catch ( AuthenticationException ae ) {logger.info("其他错误");}
        return true;
	}

	@Override
	public void logout() {
		Subject subject = SecurityUtils.getSubject();
        subject.logout();
	}
	
	@Override
	public Map<String,String> sendMsg(String phone) {
		String msg="【刘蓬】你好,登录验证码为：123456。如果本人操作请忽略此信息";
		int ret=SendMessageUtil.sendMsg("lp18408244163","d41d8cd98f00b204e980", phone, msg);
		Map<String,String> map=new HashMap<String,String>();
		map.put("code", String.valueOf(ret));
		map.put("msg", SendMessageUtil.getMessage(ret));
		return map;
	}
	
	

}
